<template>
  <div style="height: 90%;width: 100%;padding: 15px;box-sizing: border-box;">
    <!-- 查询区域 -->
    <el-form :inline="true" :model="searchForm" class="demo-form" style="margin-bottom: 15px;">
      <!-- 新增问题关键词输入框 -->
      <el-form-item label="问题">
        <el-input
            v-model="searchForm.questionMh"
            placeholder="请输入问题关键词"
            style="width: 200px;"
        ></el-input>
      </el-form-item>

      <el-form-item label="住院号">
        <el-input
            v-model="searchForm.hospitalNumber"
            placeholder="请输入住院号"
            style="width: 180px;"
        ></el-input>
      </el-form-item>

      <el-form-item label="起始时间">
        <el-date-picker
            v-model="searchForm.startTime"
            type="datetime"
            placeholder="起始时间"
            style="width: 200px;"
            :default-value="defaultStartTime"
        ></el-date-picker>
      </el-form-item>

      <el-form-item label="结束时间">
        <el-date-picker
            v-model="searchForm.endTime"
            type="datetime"
            placeholder="结束时间"
            style="width: 200px;"
        ></el-date-picker>
      </el-form-item>

      <el-form-item label="处理情况">
        <el-select
            v-model="searchForm.status"
            placeholder="请选择处理情况"
            style="width: 150px;"
        >
          <el-option label="全部" value="全部"></el-option>
          <el-option label="已处理" value="true"></el-option>
          <el-option label="未处理" value="false"></el-option>
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="handleSearch">查询</el-button>
      </el-form-item>
    </el-form>

    <!-- 表格区域 -->
    <el-table
        :data="tableData"
        border
        style="width: 100%;"
        :height="tableHeight"
        :row-style="{ height: 'auto' }"
        :cell-style="{ padding: '8px' }">
      <el-table-column
          prop="hospitalNumber"
          label="住院号"
          min-width="100">
      </el-table-column>
      <el-table-column
          prop="questionText"
          label="问题"
          min-width="250">
        <!-- 使用v-slot语法 -->
        <template #default="scope">
          <div class="text-wrap">{{ scope.row.questionText }}</div>
        </template>
      </el-table-column>
      <el-table-column
          prop="answerText"
          label="答案"
          min-width="250">
        <template #default="scope">
          <div class="text-wrap">{{ scope.row.answerText }}</div>
        </template>
      </el-table-column>
      <el-table-column
          prop="questionStatus"
          label="问题状态"
          min-width="100">
        <template #default="scope">
          <el-tag :type="scope.row.questionStatus === '已处理' ? 'success' : 'info'">
            {{ scope.row.questionStatus }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column
          prop="answerStatus"
          label="答案状态"
          min-width="100">
        <template #default="scope">
          <el-tag :type="scope.row.answerStatus === '启用' ? 'success' : 'warning'">
            {{ scope.row.answerStatus }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column
          prop="createTime"
          label="处理时间"
          min-width="160">
      </el-table-column>
      <el-table-column
          prop="handler"
          label="处理人"
          min-width="100">
      </el-table-column>
      <el-table-column
          fixed="right"
          label="操作"
          min-width="160">
        <template #default="scope">
          <el-button @click="handleProcess(scope.row)" size="small" style="color: #409EFF;">处理</el-button>
          <el-button @click="handleForward(scope.row)" size="small" style="color: #67C23A;">转发</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页控件 -->
    <div style="text-align: right; margin-top: 10px;">
      <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="pagination.currentPage"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="pagination.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pagination.total">
      </el-pagination>
    </div>

    <!-- 处理弹窗 -->
    <el-dialog title="处理问题" v-model="processDialogVisible" width="600px" :close-on-click-modal="false">
      <el-form :model="processForm" ref="processForm" :rules="rules" label-position="left">
        <el-form-item label="住院号" :label-width="formLabelWidth">
          <el-input v-model="processForm.hospitalNumber" disabled></el-input>
        </el-form-item>
        <el-form-item label="问题" :label-width="formLabelWidth">
          <el-input type="textarea" v-model="processForm.questionText" disabled :rows="4"></el-input>
        </el-form-item>
        <el-form-item label="答案" :label-width="formLabelWidth" prop="answerText">
          <el-input type="textarea" v-model="processForm.answerText" :rows="6" placeholder="请输入回答内容，最多120个字符"></el-input>
          <div style="color: #666; font-size: 12px; margin-top: 5px; text-align: right;">
            {{ processForm.answerText ? processForm.answerText.length : 0 }}/120
          </div>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="processDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitAnswer">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { apiClient } from '../api/apiClient'

export default {
  data() {
    return {
      // 查询表单，添加questionMh字段
      searchForm: {
        hospitalNumber: '全部',
        startTime: null,
        endTime: null,
        status: '全部',
        questionMh: ''  // 新增问题关键词查询条件
      },
      defaultStartTime: null,

      // 表格数据
      tableData: [],

      // 分页信息
      pagination: {
        currentPage: 1,
        pageSize: 10,
        total: 0
      },

      tableHeight: 'calc(100vh - 220px)',

      // 处理弹窗
      processDialogVisible: false,
      processForm: {
        id: null,
        hospitalNumber: '',
        questionText: '',
        answerText: ''
      },

      formLabelWidth: '100px',

      // 表单验证规则
      rules: {
        answerText: [
          { required: true, message: '请输入答案', trigger: 'blur' },
          { max: 120, message: '答案不能超过120个字符', trigger: 'blur' }
        ]
      }
    };
  },
  created() {
    // 初始化起始时间为当前时间（精确到小时）
    const now = new Date();
    this.defaultStartTime = new Date(now.getFullYear(), now.getMonth(), now.getDate(), now.getHours(), 0, 0);
    this.searchForm.startTime = this.defaultStartTime;

    // 加载数据
    this.fetchData();
  },
  methods: {
    // 处理查询
    handleSearch() {
      this.pagination.currentPage = 1;
      this.fetchData();
    },

    // 处理每页条数变化
    handleSizeChange(val) {
      this.pagination.pageSize = val;
      this.pagination.currentPage = 1;
      this.fetchData();
    },

    // 处理页码变化
    handleCurrentChange(val) {
      // 验证页码有效性
      if (val < 1) {
        this.pagination.currentPage = 1;
      } else if (this.pagination.total > 0 && val > Math.ceil(this.pagination.total / this.pagination.pageSize)) {
        this.pagination.currentPage = Math.ceil(this.pagination.total / this.pagination.pageSize);
      } else {
        this.pagination.currentPage = val;
      }
      this.fetchData();
    },

    // 获取数据
    fetchData() {
      // 处理状态参数
      let statusParam = null;
      if (this.searchForm.status === 'true') {
        statusParam = true;
      } else if (this.searchForm.status === 'false') {
        statusParam = false;
      }

      const params = {
        authority: localStorage.getItem('authority'),
        hospitalNumber: this.searchForm.hospitalNumber,
        startTime: this.searchForm.startTime ? this.formatDateTime(this.searchForm.startTime) : null,
        endTime: this.searchForm.endTime ? this.formatDateTime(this.searchForm.endTime) : null,
        status: statusParam,
        pageNum: this.pagination.currentPage,
        pageSize: this.pagination.pageSize,
        questionMh: this.searchForm.questionMh || null  // 新增参数：问题关键词
      };

      console.log('请求参数:', params);
      // 调用接口
      apiClient.get('/messageAlert/selectQa', { params })
          .then(response => {
            console.groupCollapsed('[API] /messageAlert/selectQa 响应数据');
            console.log('请求参数:', params);
            console.log('完整响应:', response);
            console.log('响应状态码:', response.status);
            console.log('业务状态码:', response.data.code);
            console.log('业务消息:', response.data.msg || '无消息');
            console.log('数据条数:', response.data.data?.list);
            console.log('总记录数:', response.data.data?.total || 0);
            console.groupEnd();
            if (response.data.code === 1) {
              this.tableData = response.data.data.list || [];
              this.pagination.total = response.data.data.total || 0;

              console.log('recept:', this.tableData);
              // 格式化数据
              this.tableData.forEach(item => {
                // 处理问题状态 - 根据questionStatus字段
                item.questionStatus = item.questionStatus ? '已处理' : '未处理';
                // 处理答案状态 - 根据answerStatus字段
                item.answerStatus = item.isused ? '启用' : '禁用';
                // 格式化时间
                if (item.createTime) {
                  item.createTime = this.formatDateToStr(new Date(item.createTime));
                }
              });
              console.log('改造后:', this.tableData);
            } else {
              this.$message.error('获取数据失败：' + (response.data.msg || '未知错误'));
            }
          })
          .catch(error => {
            console.error('获取数据失败:', error);
            this.$message.error('网络请求失败，请稍后重试');
          });
    },

    // 处理按钮点击
    handleProcess(row) {
      this.processForm = {
        id: row.id,
        hospitalNumber: row.hospitalNumber,
        questionText: row.questionText || '',
        answerText: row.answerText || ''
      };
      this.processDialogVisible = true;
    },

    // 转发按钮点击（预留）
    handleForward(row) {
      console.groupCollapsed('answer_id', row.id);
      apiClient.post('/messageAlert/doctorGetAnswerLink', null, {
        params: { id: row.id }
      })
          .then(response => {
            console.log(response)
            if (response.data.code === 1) {
              const { questionId, token } = response.data.data;
              const link = `https://qilu.laoc.site/doctorAnswer?question_id=${questionId}&token=${token}`;

              this.$alert(`问题作答链接为：${link}`, '转发链接', {
                confirmButtonText: '确定',
                dangerouslyUseHTMLString: true,
                callback: action => {
                  // 可以在这里添加复制到剪贴板的功能
                }
              });
            } else {
              this.$message.error(response.data.msg || '获取链接失败');
            }
          })
          .catch(error => {
            console.error('获取医生回答链接失败:', error);
            this.$message.error('获取链接失败，请重试');
          });
    },

    // 提交回答
    submitAnswer() {
      this.$refs.processForm.validate(valid => {
        if (valid) {
          this.$confirm('确定提交修改吗？', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            const params = {
              id: this.processForm.id,
              answerText: this.processForm.answerText,
              userId: localStorage.getItem('user_id')
            };

            apiClient.post('/messageAlert/nurseAnswer', params)
                .then(response => {
                  if (response.data.code === 1) {
                    this.$message.success('成功提交回答');
                    this.processDialogVisible = false;
                    this.fetchData(); // 重新加载数据
                  } else {
                    this.$message.error(response.data.msg || '提交失败');
                  }
                })
                .catch(error => {
                  console.error('提交回答失败:', error);
                  this.$message.error('网络请求失败，请稍后重试');
                });
          }).catch(() => {
            // 取消操作，不做处理
          });
        }
      });
    },

    // 格式化日期时间为字符串（传给后端）
    formatDateTime(date) {
      if (!date) return null;
      const d = new Date(date);
      const pad = num => (num < 10 ? '0' + num : num);
      return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())} ${pad(d.getHours())}:${pad(d.getMinutes())}:${pad(d.getSeconds())}`;
    },

    // 格式化日期为友好显示
    formatDateToStr(date) {
      if (!date) return '';
      const d = new Date(date);
      const pad = num => (num < 10 ? '0' + num : num);
      return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())} ${pad(d.getHours())}:${pad(d.getMinutes())}:${pad(d.getSeconds())}`;
    }
  }
};
</script>

<style scoped>
.text-wrap {
  white-space: pre-wrap;
  word-wrap: break-word;
  line-height: 1.5;
  max-height: 120px;
  overflow: auto;
  /* 实现17个汉字换行 */
  letter-spacing: normal;
  word-break: break-all;
}

::v-deep .el-textarea__inner {
  resize: none;
}

::v-deep .el-dialog__body {
  padding: 20px;
}

::v-deep .el-pagination {
  margin-top: 15px;
}
</style>
